import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
import 'package:zhuanzu/utils/api.dart';

import '../provider/AuthProvider.dart';
import '../provider/UserProvider.dart';
import '../widgets/FollowButton.dart';
import 'post_grid_view_simple.dart';

class UserProfilePage extends StatefulWidget {
  final String userId;
  final String nickname;

  const UserProfilePage({
    super.key,
    required this.userId,
    required this.nickname,
  });

  @override
  State<UserProfilePage> createState() => _UserProfilePageState();
}

class _UserProfilePageState extends State<UserProfilePage> {
  int _pageNum = 1;
  final int _pageSize = 20;
  bool _isLoading = false;
  bool _hasMore = true;

  final List<Map<String, dynamic>> _posts = [];

  final ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    super.initState();

    WidgetsBinding.instance.addPostFrameCallback((_) {
      context.read<UserProvider>().fetchUserInfo(widget.userId);
    });

    _loadMorePosts();

    _scrollController.addListener(() {
      if (_scrollController.position.pixels >=
          _scrollController.position.maxScrollExtent - 200) {
        _loadMorePosts();
      }
    });
  }

  Future<void> _loadMorePosts() async {
    if (_isLoading || !_hasMore) return;

    setState(() {
      _isLoading = true;
    });

    final res = await Api.get(
      '/cms/post/listByUser',
      params: {
        'userId': widget.userId,
        'pageNum': _pageNum,
        'pageSize': _pageSize,
      },
    );

    if (res['code'] == 0) {
      final records = List<Map<String, dynamic>>.from(res['data']['records']);
      final total = res['data']['total'] ?? 0;

      setState(() {
        _posts.addAll(records);
        _pageNum++;
        _hasMore = _posts.length < total;
        _isLoading = false;
      });
    } else {
      setState(() {
        _isLoading = false;
        _hasMore = false;
      });
    }
  }

  void _goToChat() {
    final myId = context.read<AuthProvider>().userId ?? '';
    context.push(
      '/chat?nickname=${widget.nickname}&userId=${widget.userId}&myId=$myId',
    );
  }

  void _toggleFollow() {
    // 这里写关注/取关逻辑
  }

  @override
  Widget build(BuildContext context) {
    final userProvider = context.watch<UserProvider>();

    return Scaffold(
      appBar: AppBar(automaticallyImplyLeading: false),
      body: RefreshIndicator(
        onRefresh: () async {
          // 刷新用户信息和帖子列表
          await context.read<UserProvider>().fetchUserInfo(widget.userId);

          setState(() {
            _posts.clear();
            _pageNum = 1;
            _hasMore = true;
          });
          await _loadMorePosts();
        },
        child: CustomScrollView(
          controller: _scrollController,
          slivers: [
            SliverToBoxAdapter(
              child: Padding(
                padding: const EdgeInsets.symmetric(
                  horizontal: 16,
                  vertical: 16,
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        CircleAvatar(
                          radius: 50,
                          backgroundImage: userProvider.avatarUrl != null
                              ? NetworkImage(userProvider.avatarUrl!)
                              : const AssetImage(
                                      'assets/default_bg_compressed.webp',
                                    )
                                    as ImageProvider,
                        ),
                        const SizedBox(width: 16),
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                userProvider.nickname ?? '匿名用户',
                                style: const TextStyle(
                                  fontSize: 20,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                              const SizedBox(height: 6),
                              if (userProvider.phone != null &&
                                  userProvider.phone!.isNotEmpty)
                                Text(
                                  '账号: ${userProvider.phone}',
                                  style: const TextStyle(
                                    fontSize: 14,
                                    color: Colors.grey,
                                  ),
                                ),
                              Text(
                                'ip属地: ${userProvider.ipLocation?.isNotEmpty == true ? userProvider.ipLocation! : '未知'}',
                                style: const TextStyle(
                                  fontSize: 14,
                                  color: Colors.grey,
                                ),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 16),

                    // 关注/粉丝/获赞/收藏
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      children: [
                        _buildCountColumn(
                          '关注',
                          userProvider.followingCount ?? 0,
                        ),
                        _buildCountColumn(
                          '粉丝',
                          userProvider.followersCount ?? 0,
                        ),
                        _buildCountColumn('获赞', userProvider.likeCount ?? 0),
                        _buildCountColumn(
                          '收藏',
                          userProvider.favoriteCount ?? 0,
                        ),
                      ],
                    ),

                    const SizedBox(height: 16),

                    // 关注 和 私信 按钮
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        FollowButton(userId: widget.userId),
                        const SizedBox(width: 16),
                        OutlinedButton(
                          onPressed: _goToChat,
                          child: const Text('私信'),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),

            SliverPadding(
              padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
              sliver: PostGridViewSimple(posts: List.from(_posts)),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildCountColumn(String label, int count) {
    return Column(
      children: [
        Text(
          '$count',
          style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
        ),
        const SizedBox(height: 4),
        Text(label, style: const TextStyle(fontSize: 12, color: Colors.grey)),
      ],
    );
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }
}
